package com.liuh.okhttp.builder;

import java.util.LinkedHashMap;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.Request;

@SuppressWarnings("unchecked")
/**
 * @note RequestBuilder基本构造
 * @author liuh
 * */
public abstract class OkHttpRequestBuilder<T extends OkHttpRequestBuilder<?>> {
	protected String url;
	protected Map<String, String> headers;
	protected Map<String, String> params;

	public T url(String url) {
		this.url = url;
		return (T) this;
	}

	public T headers(Map<String, String> headers) {
		this.headers = headers;
		return (T) this;
	}

	public T addHeader(String key, String val) {
		if (this.headers == null) {
			headers = new LinkedHashMap<>();
		}
		headers.put(key, val);
		return (T) this;
	}

	/**
	 * @note 封装基本的request(url、head)
	 * @author liuh
	 * */
	protected Request.Builder builderBaseRequest() {
		Request.Builder mBuilder = new Request.Builder();
		mBuilder.url(url);
		appendHeaders(mBuilder);
		return mBuilder;
	}

	/**
	 * @note 封装head属性
	 * @author liuh
	 * */
	private void appendHeaders(Request.Builder builder) {
		Headers.Builder headerBuilder = new Headers.Builder();
		if (headers == null || headers.isEmpty()) {
			addHeader(
					"User-Agent",
					"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36");
		}
		for (String key : headers.keySet()) {
			headerBuilder.add(key, headers.get(key));
		}
		builder.headers(headerBuilder.build());
	}

	/**
	 * @note 在基本的request基础上封装其他属性(param)
	 * @author liuh
	 * */
	public abstract Request builderRequest();

}
